<template>
  <div class="exam-paper">
    <ul v-loading="loading" element-loading-text="数据加载中...">
      <li v-for="ele in listData" :key="ele.id" @click="downItem(ele)">
        {{ ele.name }}
      </li>
    </ul>
  </div>
  <!--  下载弹窗-->
  <el-dialog
    v-model="downDialog"
    title="真题下载"
    width="30%"
    :before-close="handleClose"
  >
    <el-input
      v-model="email"
      placeholder="请输入邮箱地址"
      @change="emailChange"
    ></el-input>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          color="#ff7214"
          style="color: #fff"
          @click="confirmDowm"
          >下载</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, defineProps } from "vue";
import { ElMessage } from "element-plus";
import { download, question } from "@/api/api";
import { decrypt } from "@/utils/parseDate";
const loading = ref(false);
const props = defineProps({
  majorId: String,
});
const email = ref("");
const downDialog = ref(false);
const listData = ref([]);
const downData = ref(null);
// 校验邮箱
function emailChange(val) {
  const reg =
    /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
  if (!reg.test(val)) {
    ElMessage.error("请输入正确的邮箱地址!");
    return;
  }
  email.value = val;
}
// 获取考研真题
async function getQuestion() {
  try {
    loading.value = true;
    const data = {
      majorOutRelationId: props.majorId,
    };
    const result = await question(data);
    const res = JSON.parse(decrypt(result));
    if (res.status === 0) {
      listData.value = res.result;
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
    // throw new Error(e)
  }
}
// 下载真题弹窗
function downItem(ele) {
  downData.value = ele;
  downDialog.value = true;
}
function handleClose() {
  downData.value = null;
  email.value = "";
  downDialog.value = false;
}
// 下载真题
async function confirmDowm() {
  try {
    const data = {
      examPaperName: downData.value.name,
      id: downData.value.id,
      majorOutRelationId: props.majorId,
    };
    const result = await download(data);
    const res = JSON.parse(decrypt(result));
    if (res.status === 0) {
      ElMessage.success("下载成功!");
      downDialog.value = false;
      email.value = "";
      downData.value = null;
    }
  } catch (e) {
    // throw new Error(e)
  }
}
onMounted(() => {
  getQuestion();
});
</script>
<style lang="less" scoped>
.exam-paper {
  ul {
    margin: 0;
    padding: 0;
    li {
      list-style: none;
      padding: 0;
      margin: 0;
      height: 44px;
      line-height: 44px;
      color: #e6a23c;
      font-size: 16px;
      cursor: pointer;
      width: max-content;
    }
  }
}
</style>
